package com.wcity.manage.common.utils;

import com.wcity.manage.common.context.Constants;
import net.jielan.utils.IOUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * HttpServletRequest辅助工具
 *
 * @author dy
 */
public class RequestUtil {

	/**
	 * 获取Request请求所有参数
	 *
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static Map<String, String> getFromsRequest( HttpServletRequest request ) throws IOException {
		
		if ( "POST".equals( request.getMethod() ) ) {
			return getParamsPost( request.getInputStream() );
		}
		Enumeration<?> names = request.getParameterNames();
		Map<String, String> params = new HashMap<String, String>();
		while ( names.hasMoreElements() ) {
			String name = (String) names.nextElement();
			params.put( name, getFromRequest( request, name ) );
		}
		return params;
	}

	/**
	 * 获取Request请求参数
	 *
	 * @param request
	 * @param name
	 * @return
	 */
	public static String getFromRequest( HttpServletRequest request, String name ) {
		String val = request.getParameter(name);
		return val != null ? val.trim() : null;
	}

	/**
	 * 获取Request请求所有参数(POST)
	 *
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static Map<String, String> getParamsPost( InputStream is ) throws IOException {
		
	    Map<String, String> temp = new HashMap<String, String>();
	    String[] params = IOUtil.inputStreamToString( is, Constants.ENCODE ).split( "\\&" );
	    if ( params.length > 1 ) {
	    	for ( int i = 0 ; i < params.length ; ++i ) {
	    		String param = params[i];
	    		int idx = param.indexOf( "=" );
	    		String value = param.substring( idx + 1, param.length() );
	    		if ( value != null ) {
	    			value = URLDecoder.decode( value, Constants.ENCODE );
	    		}	
	    		temp.put( param.substring( 0, idx ), value );
	      }
	    }
	    return temp;
	}

	/**
	 * 获取访问者IP
	 *
	 * @param request
	 * @return
	 */
	public static String getIpAddr( HttpServletRequest request ) {
		String ip = request.getHeader( "X-Real-IP" );
		if ( !StringUtil.isBlank( ip ) && !"unknown".equalsIgnoreCase( ip ) ) {
			return ip;
		}
		ip = request.getHeader( "X-Forwarded-For" );
		if ( !StringUtil.isBlank( ip ) && !"unknown".equalsIgnoreCase( ip ) ) {
			// 多次反向代理后会有多个IP值，第一个为真实IP。
			int index = ip.indexOf( ',' );
			if ( index != -1 ) {
				return ip.substring( 0, index );
			} else {
				return ip;
			}
		} else {
			return request.getRemoteAddr();
		}
	}

}
